package com.wanlian.candy.controller;

import com.wanlian.candy.controller.vo.ValidataCode;
import com.wanlian.common.*;
import com.wanlian.json.JsonResult;
import com.wanlian.json.JsonStringUtil;
import com.wanlian.model.ResultModel;
import com.wanlian.util.PictureUtil;
import com.wanlian.util.QrCodeCreateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/imgcode")
public class ImageGenerateController {
    /* 验证码管理 */
    // 刷新(向服务器请求)生成验证码
    @RequestMapping(value = "/getvalidatecode")
    @ResponseBody
    public String getLoginImageCode(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");// 设置响应类型，告知浏览器输出的是图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Set-Cookie", "name=value; HttpOnly");// 设置HttpOnly属性,防止Xss攻击
        response.setDateHeader("Expire", 0);
        try {
            VerifyCodeUtils.createRandomCode(request, response, "imageCode");// 生成图片并通过response输出
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 验证码 验证
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkimgcode")
    @ResponseBody
    public String checkImgCode(@RequestBody String data, HttpServletRequest request) {
        ValidataCode code = JsonStringUtil.readValue(data, ValidataCode.class);
        // 1：获取用户输入的验证码(字符串)
        String inputValidateCode = code.getValidatecode();
        // 2：获取用户session中存储的本次生成的验证码信息(字符串)
        HttpSession session = request.getSession();
        String validateCode = (String) session.getAttribute(session.getId() + "imageCode");
        // 3：判断验证码是否输入的正确
        if (inputValidateCode.equalsIgnoreCase(validateCode)) {
            // 非空并且匹配上了
            return new JsonResult().Serailze(true);
        } else {
            return new JsonResult().Serailze(false);
        }
    }


    @RequestMapping(value = "/shareimg/{userTag}")
    @ResponseBody
    public String getShareImage(@PathVariable("userTag") String userTag,HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setContentType("application/json");
        try {
            PictureUtil pictureUtil = new PictureUtil();
          //  String dpath = "/home/java/tomcat/apache-tomcat/apache-tomcat-7.0.40-windows-x64/apache-tomcat-7.0.40/webapps/uploadfiles";
            String dpath = "/usr/local/uploadfiles";
            String filepath = dpath + "/" + userTag + ".png";
            QrCodeCreateUtil.createQrCode(new FileOutputStream(new File(filepath)), "http://www.zeerong.com/help/invite/receive.html?"+userTag, 1100, "PNG");
            pictureUtil.mergeImg(dpath + "/qr.png",
                    filepath,
                    dpath + "/img_" + userTag + ".png",
                    2.6
            );
            String img = "https://www.zeerong.com/router/upload//file/dir/img_" + userTag + ".png";
            ResultModel resultModel=new ResultModel(true);
            Map<String,String> map =new HashMap<String,String>();
            map.put("url",img);
            resultModel.setObject(map);
            return new JsonResult().Serailze(resultModel);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
